using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.IO;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Threading;

namespace CStock
{
    //using chartproject;
    //using ThreadCommunication;
    //using TimeSeriesManagement;
    //using CompareFloatingPoint = Basic.CompareFloatingPoint;


    public class YahooIntraday : DatafeedHandler
	{
	    

       
        private string url_excelSheet;
        private IList<string> shareListSymbols;
        private IList<IDataItem> shareList;
        private IList<System.IO.StreamWriter> streamWriters;
        private IList<double> quotesOld;
        private bool downloadInProgress;



       

        private System.Windows.Forms.Timer timerSaveQuotes;

        public YahooIntraday():base()
        {

            this.timerSaveQuotes = new System.Windows.Forms.Timer();
            this.timerSaveQuotes.Interval = 1000;
            shareListSymbols = new List<string>();
            shareList = new List<IDataItem>();
            streamWriters = new List<System.IO.StreamWriter>();
            quotesOld = new List<double>();
            
        }
        public IList<string> ShareListSymbols
        {
            get
            {
                return this.shareListSymbols;
            }
            set
            {
                shareListSymbols = value;
            }
        }
        private System.IO.StreamWriter CreateFile(IDataItem di)
        {
            if (!System.IO.Directory.Exists(di.DataClass.DataClassIntraday.Path))
            {
                System.IO.Directory.CreateDirectory(di.DataClass.DataClassIntraday.Path);

            }
            //if (!System.IO.Directory.Exists(di.DataClass.DataClassIntraday.Path + "\\" + di.DataClass.DataClassIntraday.ID))
            //{
            //    System.IO.Directory.CreateDirectory(di.DataClass.DataClassIntraday.Path + "\\" + di.DataClass.DataClassIntraday.ID);

            //}
            string fileName = di.DataClass.DataClassIntraday.Path + "\\" + di.DataClass.DataClassIntraday.ID + ".txt";
            System.IO.StreamWriter swriter = new System.IO.StreamWriter(fileName, true);
            return swriter;
        }
        public bool AddShareToList(IDataItem di)
        {
            
            string strName = di.Symbol;
            if(!this.shareListSymbols.Contains(strName))
            {
                this.shareListSymbols.Add(strName);
                shareList.Add(di);
                System.IO.StreamWriter swriter = CreateFile(di);
                
                streamWriters.Add(swriter);
                quotesOld.Add(0f);


            }
            CreateDownloadURL();
            return true;

        }
       
        public bool StartDownload()
        {
            this.timerSaveQuotes.Tick += new System.EventHandler(this.timerSaveQuotes_Tick);
            timerSaveQuotes.Start();
            return true;

        }
        public bool StopDownload()
        {
            this.timerSaveQuotes.Tick -= new System.EventHandler(this.timerSaveQuotes_Tick);
            timerSaveQuotes.Stop();
            for (int i = 0; i < this.streamWriters.Count; i++)
            {
                try
                {
                    this.streamWriters[i].Close();
                }
                catch
                {
                }

            }
            return true;

        }
        private bool CreateDownloadURL()
        {
            DateTime dt = DateTime.Now;
            this.url_excelSheet = @"http://download.finance.yahoo.com/d/quotes.csv?s=";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.shareListSymbols.Count; i++)
            {
                //string strSymbol = portf.DataItems[i].Symbol_Intraday;
                string strSymbol = shareListSymbols[i];
                if (!string.IsNullOrEmpty(strSymbol))
                {
                    //sb.Append(portf.DataItems[i].Symbol_Intraday + ",");
                    sb.Append(strSymbol + ",");

                }


            }
            string shareList = sb.ToString();
            shareList = shareList.Remove(shareList.Length - 1, 1);

            url_excelSheet += shareList;
            url_excelSheet += @"&f=st5l9c6p4b1a3&e=.csv";

            
            
            return true;

        }
        private bool DownloadIntradayQuotes()
        {

            downloadInProgress = true;
            //this.RaiseObjectChangedEvent(this, "Download init for: " + dataItem.ID, dataItem, dataItem);

            
            StringCollection strCollection = ReadPage_ToStringCollection(url_excelSheet);
            if (strCollection == null || strCollection.Count == 0)
                return false;
            else
            {
                for (int i = 0; i < strCollection.Count; i++)
                {
                    double fClose = ReadIntradayLine(strCollection[i]);
                    if (fClose != 0f && fClose != quotesOld[i])
                    {
                        quotesOld[i] = fClose;
                        string strQuoteLine = CreateQuoteString(fClose);
                        streamWriters[i].WriteLine(strQuoteLine);
                        streamWriters[i].Flush();

                    }
                    
                }
                

              
            }
           
            downloadInProgress = false;
            return true;

        }
        private string CreateQuoteString(double fClose)
        {
            string strOutput = string.Empty;
            strOutput += DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + "&" + Convert.ToString(fClose, System.Globalization.CultureInfo.InvariantCulture);
            return strOutput;
        }
        private double ReadIntradayLine(string line)
        {
            //IQuote qu = new Quote();
            double fClose = 0f;
            try
            {
                
                string[] listQuotes = line.Split(new Char[] { ',' });

                fClose = Convert.ToDouble(listQuotes[2], CUtil.Conversions.CultureAmerican);
                return fClose;
            }
            catch 
            {
                //do nothing
                //Debug.Assert(false, "Error ReadYahooList : " + dataItem.ID + " ; " + ex.Message);
                return fClose;
            }

        }
        private void timerSaveQuotes_Tick(object sender, System.EventArgs e)
        {
            if(!downloadInProgress)
                DownloadIntradayQuotes();
                        
        }
	}
}